import json
import logging
import traceback
from datetime import datetime
from functools import wraps
from flask import request, jsonify


# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def json_serial(obj):
    """JSON 序列化函数，处理日期类型"""
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(f"Type {type(obj)} not serializable")


def jsonify_result(data=None, message='Success', status=200, errors=None):
    """统一的响应格式化函数"""
    response = {
        'status': 'success' if status < 400 else 'error',
        'message': message,
        'data': data,
        'errors': errors,
        'timestamp': datetime.utcnow().isoformat()
    }
    return jsonify(response), status


def api_error_handler(func):
    """API 错误处理装饰器"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            logger.error(f"Error in {func.__name__}: {str(e)}")
            logger.debug(traceback.format_exc())
            
            # 根据异常类型返回不同的错误信息
            if isinstance(e, ValueError):
                return jsonify_result(
                    message='Invalid input',
                    errors=str(e),
                    status=400
                )
            elif isinstance(e, KeyError):
                return jsonify_result(
                    message='Missing required field',
                    errors=str(e),
                    status=400
                )
            else:
                return jsonify_result(
                    message='Internal server error',
                    errors='An unexpected error occurred',
                    status=500
                )
    return wrapper


def validate_json(fields=None):
    """验证 JSON 请求数据装饰器"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            # 检查请求是否为 JSON
            if not request.is_json:
                return jsonify_result(
                    message='Request must be JSON',
                    status=400
                )
            
            # 获取 JSON 数据
            data = request.get_json()
            
            # 验证必填字段
            if fields:
                missing_fields = [field for field in fields if field not in data]
                if missing_fields:
                    return jsonify_result(
                        message='Missing required fields',
                        errors=f'Required fields: {missing_fields}',
                        status=400
                    )
            
            return func(*args, **kwargs)
        return wrapper
    return decorator


def safe_get(data, keys, default=None):
    """安全地从嵌套字典中获取值"""
    if not isinstance(data, dict):
        return default
    
    current = data
    for key in keys.split('.'):
        if isinstance(current, dict) and key in current:
            current = current[key]
        else:
            return default
    
    return current


def clean_text(text):
    """清理文本内容"""
    if not text:
        return ''
    
    # 移除多余的空白字符
    import re
    text = re.sub(r'\s+', ' ', text)
    # 移除首尾空白
    text = text.strip()
    
    return text